package org.demo.jdbctemplate.dao.impl;

import org.demo.jdbctemplate.dao.IUserDao;
import org.demo.jdbctemplate.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.Collections;
import java.util.List;

@Repository
public class UserDaoImpl implements IUserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Override
    public int add(User user) {
        return jdbcTemplate.update("insert into user(name, age) values(?, ?)", user.getName(), user.getAge());
    }

    @Override
    public int update(User user) {
        return jdbcTemplate.update("update user set name = ?, age = ? where id = ? ",
                user.getName(), user.getAge(), user.getId());
    }

    @Override
    public int delete(long id) {
        return jdbcTemplate.update("delete from user where id = ?", id);
    }

    @Override
    public User findUserById(long id) {
        List<User> list = jdbcTemplate.query("select * from user where id = ?",
                new Object[]{id}, new BeanPropertyRowMapper<>(User.class));
        if(list != null && list.size() > 0 ){
            User user = list.get(0);
            return user;
        }else {
            return null;
        }
    }

    @Override
    public List<User> findUserList() {
        List<User> list = jdbcTemplate.query("select * from user ",
                new Object[]{}, new BeanPropertyRowMapper<>(User.class));
        if(list != null && list.size() > 0 ){
            return list ;
        }else {
            return Collections.emptyList();
        }
    }
}
